var contactsService;
var contactsFeedUri = 'http://www.google.com/m8/feeds/contacts/default/full';
var contactScope = 'http://www.google.com/m8/feeds';
var contacts = new Array();

function setupContactsService() {
	contactsService = new google.gdata.contacts.ContactsService('team4-collegeMaps-1.0');
}

function allowContacts() {
	var contactToken = google.accounts.user.login(contactScope);
}

function initContacts() {
	setupContactsService();
	getMyContacts();
}

function getMyContacts() {
	if (google.accounts.user.checkLogin(contactScope)) {
		var query = new google.gdata.contacts.ContactQuery(contactsFeedUri);
		contactsService.getContactFeed(query, handleContactsFeed, handleContactsError);
	}
}

var handleContactsFeed = function(result) {
	if (google.accounts.user.checkLogin(contactScope)) {
		var entries = result.feed.entry;
		var contactPanel = document.getElementById("contacts");	
		var code =  '<ul>';
		
		for (var i = 0; i < entries.length; i++) {
			var contactEntry = entries[i];
			
			var name = contactEntry.getTitle().getText();
			var email = contactEntry.getEmailAddresses();
			var phone =  contactEntry.getPhoneNumbers();
			
			if (email.length > 0) {
				email = email[0].getAddress();
			} else {
				email = "Unlisted";
			}
			
			if (phone.length > 0) {
				phone = phone[0].getValue();
			} else {
				phone = "Unlisted";
			}
			
			contacts.push(contactEntry);
		
			code += "<li><table>" + (name != "" ? "<tr><th>Name:</th><td>" + name + "</td></tr>" : "") + "<tr><th>Email:</th><td>" + email + "</td></tr><tr><th>Phone:</th><td>" + phone + "</td></tr></table></li>";
		}
		
		code += "</ul>";	
		contactPanel.innerHTML += code;
	}
}

function handleContactsError(e) {
	alert("An error has occurred with the contacts.\n" + e.cause ? e.cause.statusText : e.message);
}

function makeContact(latlng) {
	// Create an instance of ContactEntry
	var entry = new google.gdata.contacts.ContactEntry();

	// Set the name of the contact
	entry.setTitle(google.gdata.Text.create(document.placeContactForm.name.value));

	// Create an email instance
	var email = new google.gdata.Email();
	email.setAddress(document.placeContactForm.email.value);
	email.setPrimary(true);
	// Designate this email as the "home" email
	email.setRel(google.gdata.Email.REL_HOME);

	// Add the email instance
	entry.setEmailAddresses([email]);
	
	entry.setContent("latlng" + latlng);
	
	contactsService.insertEntry(contactsFeedUri, entry, reloadPage, handleContactsError, google.gdata.contacts.ContactEntry);
}